﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace QuickPasteItLib
{
    public class UbuntuPasteBin : IPasteBin
    {
        /// <summary>
        /// Submits the given text to the pastebin.
        /// </summary>
        /// <param name="paste">The text to be pasted.</param>
        /// <param name="lang">The language for syntax highlighting.</param>
        /// <returns>The URL of the paste on success, an empty string on failure.</returns>
        public string SubmitPaste(string paste, PasteLang lang = PasteLang.Plain, string author = "Anonymous")
        {
			string result = HttpTools.GetRedirectLocationFromResponse(
					HttpTools.HttpRequest(
						"http://paste.ubuntu.com",
						"content=" + HttpUtility.UrlEncode(paste) +
						"&syntax=" + GetLangAbbr(lang) +
						"&poster=" + HttpUtility.UrlEncode(author),
						HttpTools.HttpReqType.POST)
                    ).Trim();

            if (!result.StartsWith("http:") && !result.StartsWith("https:"))
				 return "";
			else return result;
		}

        /// <summary>
        /// Gets the appropriate abbreviation for the given language for Vpaste.
        /// </summary>
        /// <param name="lang">Language to find abbreviation for.</param>
        /// <returns>Abbreviation suitable for use in URL.</returns>
        private string GetLangAbbr(PasteLang lang)
        {
            var abbrMap = new Dictionary<PasteLang, string>
            {
                {PasteLang.Bash, "bash"},
                {PasteLang.C, "c"},
                {PasteLang.Cpp, "cpp"},
                {PasteLang.CSharp, "csharp"},
                {PasteLang.CSS, "css"},
                {PasteLang.Haskell, "haskell"},
                {PasteLang.HTML, "html"},
                {PasteLang.Java, "java"},
                {PasteLang.JavaScript, "js"},
                {PasteLang.Perl, "perl"},
                {PasteLang.PHP, "php"},
                {PasteLang.Python, "python"},
                {PasteLang.Ruby, "rb"},
                {PasteLang.SQL, "sql"},
                {PasteLang.Tex, "tex"},
                {PasteLang.VB, "vb.net"},
                {PasteLang.XML, "xml"},
            };

            if (abbrMap.Keys.Contains(lang))
                return abbrMap[lang];
            else
                return "text";
        }
    }
}
